<template>
  <div>
    <a-modal :title="type == 'add' ? '新增包装' : '编辑包装'" :visible="visible" @before-open="open" @before-ok="handleOk" @cancel="handleCancel" :align-center="false" title-align="start" width="1000px" :mask-closable="false">
      <div>
        <a-form auto-label-width ref="formRef" size="medium" :model="form" :rules="rules">
          <a-space direction="vertical" :size="24">
            <a-row>
              <a-col :span="24">
                <a-form-item field="skuName" label="包装名称">
                  <a-input v-model="form.skuName" :max-length="200" show-word-limit />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="sku" label="SKU">
                  <a-input v-model="form.sku" max-length="50" show-word-limit :disabled="type == 'edit' ? true : false">
                    <template #append>
                      <a-button :disabled="type == 'edit' ? true : false" type="primary" @click="autoCreateSpu" :loading="autoCreateSpuLoading">生成SKU</a-button>
                    </template>
                  </a-input>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="volumn" label="长宽高" :rules="rules.volumn">
                  <a-space>
                    <a-input v-model="form.lengthNum" />
                    <div>×</div>
                    <a-input v-model="form.widthNum" />
                    <div>×</div>
                    <a-input v-model="form.heightNum" />
                    <div>（cm）</div>
                  </a-space>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="weightNum" label="重量">
                  <a-space>
                    <a-input v-model="form.weightNum" />
                    <div>（g）</div>
                  </a-space>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="关联店铺">
                  <a-select placeholder="请选择" v-model="form.sellerMarketId" multiple allow-search max-tag-count="1" allow-clear>
                    <a-option v-for="item of shopList" :value="item.sellerMarketId" :label="item.shopName"></a-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-space>
        </a-form>
      </div>

      <div class="title-bar">图片</div>

      <a-space class="mt10 mb10">
        <a-button class="gray-outline" @click="del">删除</a-button>
        <a-checkbox v-model="checkedAll" @change="selAll">全选</a-checkbox>
      </a-space>
      <div class="clearfix">
        <ul class="img-con clearfix fl">
          <div class="draggered-con">
            <li v-for="(item, index) of productPicList" :data-index="index" class="fl">
              <div class="master-map" v-if="index == 0"> 主图 </div>

              <div class="check-box">
                <a-checkbox v-model="item.checked"></a-checkbox>
              </div>

              <div class="mask">
                <div class="btn-con">
                  <icon-eye class="cursor" style="margin-right: 15px" @click.stop="showImgPre(index)" />
                  <icon-delete class="cursor" @click.stop="productPicList.splice(index, 1)" />
                </div>
              </div>
              <a-image :src="item.url" width="100%" height="100%" />
            </li>
          </div>
          <a-image-preview-group v-model:visible="imgVisible" v-model:current="current" infinite :srcList="productPicList.map((e:any) => e.url)" />
          <a-upload class="fl" v-if="productPicList.length < 10" style="width: 160px" list-type="picture-card" action="/" :on-before-upload="beforeUplaod" />
        </ul>

        <div style="font-size: 10px; color: #999999">已上传{{ productPicList.length }}/10张(支持JPG/PNG/BMP/GIF格式,图片大小不能超过5M)</div>
      </div>

      <template #footer>
        <a-button class="gray-outline" @click="handleCancel">取消</a-button>
        <a-button type="primary" :loading="loading" @click="handleOk">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, computed, nextTick } from 'vue'
  import { genSkuByConfig, saveOrUpdatePack, packDetail } from '@/api/product'
  import { updatePackageWarehouse } from '@/api/order'
  import { Message } from '@arco-design/web-vue'
  import { uplaodImg } from '@/api/base'
  import Sortable from 'sortablejs'
  import { onMounted } from 'vue'
  export default defineComponent({
    props: ['type', 'shopList', 'info'],
    setup(props: any, { emit }) {
      let visible = ref(false)
      const formRef = ref()

      const data: any = reactive({
        form: {},
        rules: {
          skuName: [{ required: true, message: '请输入包装名称' }],
          sku: [{ required: true, message: '请输入SKU' }],
          weightNum: [{ required: true, message: '请输入重量' }],
          volumn: [
            {
              required: true,
              validator: (value: any, cb: any) => {
                return new Promise((resolve: any) => {
                  if (!data.form.lengthNum) {
                    cb('请输入长')
                  }
                  if (!data.form.widthNum) {
                    cb('请输入宽')
                  }
                  if (!data.form.heightNum) {
                    cb('请输入高')
                  }
                  resolve()
                })
              },
            },
          ],
        },
        loading: false,
        houseList: [],
        autoCreateSpuLoading: false,
        productPicList: [],
        imgVisible: false,
        current: 1,
        checkedAll: false,
      })

      const open = () => {
        if (props.type == 'edit') getDetail()
      }

      const getDetail = async () => {
        const res: any = await packDetail(props.info.id)
        data.form = res?.data || {}
        if (data.form.shopList) {
          data.form.sellerMarketId = data.form.shopList.map((e: any) => e.sellerMarketId)
        }
        data.form.lengthNum = data.form?.volume?.length || ''
        data.form.widthNum = data.form?.volume?.width || ''
        data.form.heightNum = data.form?.volume?.height || ''
        data.form.weightNum = data.form?.weight?.weight || ''
        data.productPicList = data.form?.productPicList || []
      }

      const handleOk = () => {
        formRef.value.validate(async (valid: any) => {
          if (!valid) {
            let params: any = {
              ...data.form,
              volume: {
                height: data.form.heightNum,
                length: data.form.lengthNum,
                unit: 'cm',
                width: data.form.widthNum,
              },
              weight: {
                unit: 'g',
                weight: data.form.weightNum,
              },
              productPicList: data.productPicList,
              skuType: 'PACKING',
              status: 'ACTIVE',
            }

            if (data.form.sellerMarketId) {
              let arr: any = []
              data.form.sellerMarketId.forEach((e: any) => {
                let item: any = props.shopList.find((el: any) => e == el.sellerMarketId)
                if (item) {
                  let obj = {
                    marketplaceId: item?.marketplaceId || '',
                    name: item?.shopName || '',
                    sellerId: item?.sellerId || '',
                    sellerMarketId: item?.sellerMarketId || '',
                  }
                  arr.push(obj)
                }
              })
              params.shopList = arr
            }

            try {
              data.loading = true
              const res: any = await saveOrUpdatePack([params])
              if (res.code == 'SUCCESS') {
                props.type == 'add' ? Message.success('包装新增成功') : Message.success('包装编辑成功')
                handleCancel()
                emit('save')
              }
            } catch (error) {}
            data.loading = false
          }
        })
      }

      const handleCancel = () => {
        data.form = {}
        formRef.value.resetFields()
        formRef.value.clearValidate()
        data.productPicList = []
        visible.value = false
      }

      const autoCreateSpu = async () => {
        // return Message.warning('待后端接口联调')
        data.autoCreateSpuLoading = true
        const res = await genSkuByConfig({ categoryId: data.form.categoryId })
        data.autoCreateSpuLoading = false
        data.form.sku = res?.data || ''
        formRef.value.clearValidate()
      }

      const checkVolumnNum = (record: any) => {
        console.log(record)
      }

      const beforeUplaod = async (file: any) => {
        let type = file.type.split('/')[1]
        if (!['JPG', 'PNG', 'BMP', 'GIF', 'JPEG'].includes(type.toUpperCase())) {
          Message.error('请上传JPG/PNG/BMP/GIF/JPEG格式的图片')
          return false
        }
        if (file.size / 1024 / 1024 > 5) {
          Message.error('图片最大为5M')
          return false
        }
        let formData = new FormData()
        formData.append('file', file)
        const res: any = await uplaodImg(formData)
        if (res) {
          let obj = {
            url: res.data.publicUrl,
          }
          data.productPicList.push(obj)
        }
      }

      const rowDrop = () => {
        const body: any = document.querySelector('.draggered-con')
        Sortable.create(body, {
          animation: 200, // 定义排序动画的时间
          forceFallback: true,
          onEnd(evt: any) {
            data.productPicList.splice(evt.newIndex, 0, data.productPicList.splice(evt.oldIndex, 1)[0])
            var newArray = data.productPicList.slice(0)
            data.productPicList = []
            nextTick(() => {
              data.productPicList = newArray
            })
          },
        })
      }

      const showImgPre = (index: number) => {
        data.current = index
        data.imgVisible = true
      }

      const selAll = (val: boolean) => {
        data.productPicList.map((e: any) => {
          e.checked = val
          return e
        })
      }

      const del = () => {
        let noDelList = data.productPicList.filter((e: any) => !e.checked)
        data.productPicList = noDelList
        data.checkedAll = false
      }

      setTimeout(() => {
        rowDrop()
      }, 0)

      return {
        ...(toRefs(data) as any),
        visible,
        formRef,
        open,
        handleOk,
        handleCancel,
        autoCreateSpu,
        checkVolumnNum,
        beforeUplaod,
        showImgPre,
        selAll,
        del,
      }
    },
  })
</script>

<style lang="less" scoped>
  :deep(.arco-input-append) {
    padding: 0;
  }

  :deep(.arco-upload-picture-card) {
    width: 160px;
    height: 160px;
  }
  :deep(.arco-upload-list-picture) {
    width: 160px;
    height: 160px;
  }

  .img-con {
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    li {
      width: 160px;
      height: 160px;
      margin-right: 10px;
      margin-bottom: 5px;
      position: relative;

      .check-box {
        position: absolute;
        top: 5px;
        right: 5px;
        z-index: 2;
      }

      .master-map {
        position: absolute;
        left: 0;
        top: 0;
        background-color: #2da641;
        text-align: center;
        height: 20px;
        width: 40px;
        z-index: 5;
        font-size: 12px;
        line-height: 20px;
        color: white;
      }

      &:hover .mask {
        display: block;
      }
      .mask {
        display: none;
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 1;
        background: rgba(0, 0, 0, 0.5);

        .btn-con {
          width: 160px;
          color: white;
          font-size: 18px;
          text-align: center;
          margin-top: 76px;
          align-items: center;
        }
      }
    }
  }
</style>
